import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    id: null,
    username: '',
    email: '',
    token: '',
    isLoggedIn: false
  }),

  getters: {
    // 获取用户名
    getUserName: (state) => state.username,
    // 检查是否登录
    checkLogin: (state) => state.isLoggedIn
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.id = userInfo.id
      this.username = userInfo.username
      this.email = userInfo.email
      this.isLoggedIn = true
    },

    // 更新用户token
    setToken(token) {
      this.token = token
    },

    // 退出登录
    logout() {
      try {
        this.id = null
        this.username = ''
        this.email = ''
        this.token = ''
        this.isLoggedIn = false
        // 确保清除所有相关的本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('login_account')
        sessionStorage.clear()
    } catch (error) {
        console.error('清除用户状态失败:', error)
        throw error
    }
    }
  }
})